package com.rzt.cft.utils;

import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzt.cft.annotation.*;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**
 * MybatisPlus 查询条件解析
 */
public class ParseWrapper {
    public static QueryWrapper parseWrapper(Object t) {
        QueryWrapper wrapper = new QueryWrapper();
        Field[] fArr = ReflectUtil.getFields(t.getClass());

        for (Field field : fArr) {
            field.setAccessible(true);
            Object value = null;
            try {
                value = field.get(t);
                if (value == null || StringUtils.isBlank(value.toString())) {
                    continue;
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                continue;
            }
            String fieldName = field.getName();
            String camelFieldName = CustomUtil.camelToUnderline(fieldName);
            boolean fieldHasLikeAnno = field.isAnnotationPresent(MpLike.class);
            if (fieldHasLikeAnno) {
                wrapper.like(camelFieldName, value);
                continue;
            }
            boolean fieldHasEqAnno = field.isAnnotationPresent(MpEQ.class);
            if (fieldHasEqAnno) {
                wrapper.eq(camelFieldName, value);
                continue;
            }
            boolean fieldHasInAnno = field.isAnnotationPresent(MpIn.class);
            if (fieldHasInAnno) {
                wrapper.in(camelFieldName, value);
                continue;
            }
            boolean fieldHasBetweenAnno = field.isAnnotationPresent(MpBetween.class);
            if (fieldHasBetweenAnno) {
                genBetweenWrapper(wrapper, field, camelFieldName, value);
                continue;
            }
        }
        return wrapper;
    }

    public static void genBetweenWrapper(QueryWrapper wrapper, Field field, String camelFieldName, Object value) {
        MpBetween fieldBTAnno = field.getAnnotation(MpBetween.class);
        ConditionType type = fieldBTAnno.type();
        String fieldNameValue = fieldBTAnno.value();
        if (StringUtils.isNotBlank(fieldNameValue)) {
            camelFieldName = fieldNameValue;
        }
        if (type.equals(ConditionType.$gt)) {
            wrapper.gt(camelFieldName, value);
            return;
        }
        if (type.equals(ConditionType.$lt)) {
            wrapper.lt(camelFieldName, value);
            return;
        }
        if (type.equals(ConditionType.$gte)) {
            wrapper.ge(camelFieldName, value);
            return;
        }
        if (type.equals(ConditionType.$lte)) {
            wrapper.le(camelFieldName, value);
            return;
        }
    }

}
